﻿using System;
using System.IO;
using System.Text;
/// <summary>
/// 自定义日志存储工具
/// </summary>
namespace Liang.Util.Files
{
    public class CustomLog
    {
        private static string CreateLogFilePath()
        {
            //获取exe所在目录
            string exePath = AppDomain.CurrentDomain.BaseDirectory;
            string logFile = exePath + "log";
            if (!Directory.Exists(logFile))
            {
                Directory.CreateDirectory(logFile);
            }
            //获取当前日期的年
            string year = DateTime.Now.Year.ToString();
            logFile = logFile + "\\" + year;
            if (!Directory.Exists(logFile))
            {
                Directory.CreateDirectory(logFile);
            }
            string ymd = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            return logFile + "\\" + ymd;
        }

        public static void writeLog(string txt)
        {
            string filePath = CreateLogFilePath();
            string msg = DateTime.Now.ToString() + "  " + txt + "\n";
            using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.End);
                    sw.WriteLine(msg);
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }
            }
        }
    }
}
